package com.example.mqtt.utils;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttSenderUtil {
    private static final String Host = "tcp://127.0.0.1:1883";
    public static MqttClient mqttClient = null;

    public static void init(String clientId) throws MqttException {
        assert null != clientId : "client id is null";
        // 初始化连接设置对象
        MqttConnectOptions options = new MqttConnectOptions();
        // 客户端断开连接时清除所有状态
        options.setCleanSession(true);
        // 设置连接超时
        options.setConnectionTimeout(30);
        // 设置用户名
        options.setUserName("admin");
        // 设置密码
        options.setPassword("123456".toCharArray());
        // 初始化MqttClient
        mqttClient = new MqttClient(Host, clientId, new MemoryPersistence());
        // 设置连接和回调
        if (!mqttClient.isConnected()) {
            // 客户端添加回调函数
            mqttClient.setCallback(new MyMqttCallback());
            // 创建连接
            mqttClient.connect(options);
        }
    }

    // 发布消息
    public static void publishMessage(String pubTopic, String message, int qos) throws MqttException {
        if (null == mqttClient || !mqttClient.isConnected()) init("2");
        System.out.println("client id: " + mqttClient.getClientId());
        System.out.println("send message: " + message);
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(qos);
        mqttMessage.setPayload(message.getBytes());
        MqttTopic topic = mqttClient.getTopic(pubTopic);
        if (null != topic) {
            topic.publish(mqttMessage);
        }
    }
}
